package com.dbb.trade.service;

import com.dbb.trade.dao.PhotoDao;
import com.dbb.trade.entity.Photo;
import com.dbb.trade.util.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springside.modules.persistence.DynamicSpecifications;
import org.springside.modules.persistence.SearchFilter;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Component
@Transactional(readOnly = true)
public class PhotoManager {

	private static Logger logger = LoggerFactory.getLogger(PhotoManager.class);

	@Autowired
	private PhotoDao photoDao;

	@Transactional(readOnly = false)
	public Photo save(Photo photo) {
		logger.info(photo.toString());
		return photoDao.save(photo);
	}

	@Transactional(readOnly = false)
    public List<Photo> save(File file) {
		List<Photo> photos = new ArrayList<Photo>();
    	for(File f : FileUtils.getAllFiles(file)) {
    		photos.add(photoDao.save(new Photo(f)));
    	}
    	return photos;
    }
    @Transactional(readOnly = false)
	public void save(String fileName) {
		save(new File(fileName));
	}
    
    public List<Photo> findAll() {
        return photoDao.findAll();
    }
    
    public Page<Photo> findAll(Map<String, Object> searchParams,
                               int pageNumber, int pageSize, String sortType) {
        PageRequest pageRequest = buildPageRequest(pageNumber, pageSize, sortType);
        for(String key : searchParams.keySet()) {
            if(searchParams.get(key) == null || "".equals(searchParams.get(key).toString())) {
                searchParams.remove(key);
            }
        }
        Map<String, SearchFilter> filters = SearchFilter.parse(searchParams);
        Specification<Photo> spec = DynamicSpecifications
                .bySearchFilter(filters.values(), Photo.class);
        return photoDao.findAll(spec, pageRequest);

    }

    private PageRequest buildPageRequest(int pageNumber, int pagzSize, String sortType) {
        Sort sort = null;
        if ("createDate".equals(sortType)) {
            sort = new Sort(Direction.DESC, "createDate");
        } else if ("voteNum".equals(sortType)) {
            sort = new Sort(Direction.DESC, "voteNum");
        } else if ("browNum".equals(sortType)) {
            sort = new Sort(Direction.DESC, "browNum");
        } else if ("commNum".equals(sortType)) {
            sort = new Sort(Direction.DESC, "commNum");
        }
        return new PageRequest(pageNumber - 1, pagzSize, sort);
    }
}
